from QTdesigner.Ui_Miner import Ui_MainWindow
from PyQt5 import QtWidgets
from PyQt5.QtCore import QTimer, Qt, QObject, QThread
from PyQt5.QtGui import *
from modules.PlcController import PlcController
from modules.ObjectDetector import ObjectDetector
from modules.AnomalyDetector import AnomalyDetector
from threading import Lock
import numpy as np
import threading
import eventlet
import cv2 as cv
import torch
import time
import os

NoSignal = 0
UpSignal = 1
DownSignal = 2

Timeout = 2


class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow, QObject):
    output1, output2, output3, output4, output5, output6 = "", "", "", "", "", ""
    lock1, lock2, lock3 = Lock(), Lock(), Lock()
    lock4, lock5, lock6 = Lock(), Lock(), Lock()
    pix1, pix2, pix3, pix4, pix5, pix6 = None, None, None, None, None, None
    capSignal1, capSignal2, capSignal3, capSignal4, capSignal5, capSignal6 = 0, 0, 0, 0, 0, 0
    if_opened_1, if_opened_2, if_opened_3 = False, False, False
    if_opened_4, if_opened_5, if_opened_6 = False, False, False
    count_1, count_2, count_3 = 0, 0, 0
    count_4, count_5, count_6 = 0, 0, 0
    if_connect_1,  if_connect_2 = False, False
    last_time_1, last_time_2 = 0., 0.
    lock = Lock()

    def __init__(self, parent=None, source='', weights='', imgsz=640, conf_thres=0.25, iou_thres=0.45, device='cpu') -> None:
        super(MainWindow, self).__init__(parent)

        self.set_ui()
        self.init()

        self.set_capture()

        self.thread = QThread()
        self.moveToThread(self.thread)
        self.thread.started.connect(self.backStage_init)
        self.thread.start()

        print(source)
        self.set_detector(weights, imgsz, conf_thres, iou_thres, device)

    def backStage_init(self):
        self.set_plc_controller()

        self.set_thread()

        self.set_timer()

    def set_timer(self):
        if self.if_opened_1:
            self.timer1 = QTimer(self)
            self.timer1.timeout.connect(self.QLabelView1)
            self.timer1.setTimerType(Qt.PreciseTimer)
            self.timer1.start(35)

        if self.if_opened_2:
            self.timer2 = QTimer(self)
            self.timer2.timeout.connect(self.QLabelView2)
            self.timer2.setTimerType(Qt.PreciseTimer)
            self.timer2.start(35)

        if self.if_opened_3:
            self.timer3 = QTimer(self)
            self.timer3.timeout.connect(self.QLabelView3)
            self.timer3.setTimerType(Qt.PreciseTimer)
            self.timer3.start(35)

        if self.if_opened_4:
            self.timer4 = QTimer(self)
            self.timer4.timeout.connect(self.QLabelView4)
            self.timer4.setTimerType(Qt.PreciseTimer)
            self.timer4.start(35)

        if self.if_opened_5:
            self.time5 = QTimer(self)
            self.time5.timeout.connect(self.QLabelView5)
            self.time5.setTimerType(Qt.PreciseTimer)
            self.time5.start(35)

        if self.if_opened_6:
            self.timer6 = QTimer(self)
            self.timer6.timeout.connect(self.QLabelView6)
            self.timer6.setTimerType(Qt.PreciseTimer)
            self.timer6.start(35)

    def set_ui(self):
        import ctypes
        self.setupUi(self)

        self.setWindowIcon(QIcon("./miner.ico"))
        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("miner")
        # 设置窗口名
        self.setWindowTitle("Miner")

        blankImg = cv.imread("./resource/state/load_camera_failed.jpg")
        # 显示图像
        frame = QImage(
            blankImg.data, blankImg.shape[1], blankImg.shape[0], blankImg.shape[1], QImage.Format_Grayscale8)
        self.pix1 = QPixmap.fromImage(frame)
        self.pix2 = QPixmap.fromImage(frame)
        self.pix3 = QPixmap.fromImage(frame)
        self.pix4 = QPixmap.fromImage(frame)
        self.pix5 = QPixmap.fromImage(frame)
        self.pix6 = QPixmap.fromImage(frame)
        self.MainGraph11.setPixmap(self.pix1)
        self.MainGraph12.setPixmap(self.pix2)
        self.MainGraph13.setPixmap(self.pix3)
        self.MainGraph21.setPixmap(self.pix4)
        self.MainGraph22.setPixmap(self.pix5)
        self.MainGraph23.setPixmap(self.pix6)

    def init(self):
        self.serialPort = None
        self.count = 0
        self.sandBytes = 0
        self.last_time_1 = 0.

        # 危险区域
        # self.__restrictedArea1 = [[120, 80, 310, 230]]
        # self.__restrictedArea2 = [[300, 80, 430, 180], [230, 260, 380, 350]]
        # self.__restrictedArea3 = [[150, 140, 330, 270]]
        # self.__restrictedArea4 = [[140, 230, 300, 350]]
        # self.__restrictedArea5 = [[240, 20, 360, 120], [480, 20, 600, 120]]
        # self.__restrictedArea6 = [[180, 240, 340, 340]]

        self.__restrictedArea1 = [[40, 10, 320, 350]]
        self.__restrictedArea2 = [[40, 10, 380, 350]]
        self.__restrictedArea3 = [[60, 10, 400, 350]]
        self.__restrictedArea4 = [[10, 10, 320, 350]]
        self.__restrictedArea5 = [[100, 10, 430, 350]]
        self.__restrictedArea6 = [[10, 10, 340, 350]]

        self.__restrictedArea = [self.__restrictedArea1, self.__restrictedArea2, self.__restrictedArea3,
                                 self.__restrictedArea4, self.__restrictedArea5, self.__restrictedArea6]

        self.textBrowser.setText("192.168.7.30")
        self.textBrowser_2.setText("192.168.7.31")

        # 状态标志图片
        self.NormalState = cv.imread("./resource/state/Normal.jpg")
        self.DangerState = cv.imread("./resource/state/Danger.jpg")
        self.ErrorState = cv.imread("./resource/state/Error.jpg")
        self.state = None

        self.setStateGraph(1, 'Normal')
        self.infoLabel_1.setText("一部坡头猴车运行")
        self.setStateGraph(2, 'Normal')
        self.infoLabel_2.setText("一部偏口猴车运行")
        self.setStateGraph(3, 'Normal')
        self.infoLabel_3.setText("一部坡底猴车运行")
        self.setStateGraph(4, 'Normal')
        self.infoLabel_4.setText("二部坡头猴车运行")
        self.setStateGraph(5, 'Normal')
        self.infoLabel_5.setText("二部偏口猴车运行")
        self.setStateGraph(6, 'Normal')
        self.infoLabel_6.setText("二部坡底猴车运行")

        self.set_modules()

    def set_detector(self, weights, imgsz, conf_thres, iou_thres, device):
        with torch.no_grad():
            self.objectDetector1 = ObjectDetector(
                weights, imgsz, conf_thres, iou_thres, device)
            self.objectDetector2 = ObjectDetector(
                weights, imgsz, conf_thres, iou_thres, device)
            self.objectDetector3 = ObjectDetector(
                weights, imgsz, conf_thres, iou_thres, device)
            self.objectDetector4 = ObjectDetector(
                weights, imgsz, conf_thres, iou_thres, device)
            self.objectDetector5 = ObjectDetector(
                weights, imgsz, conf_thres, iou_thres, device)
            self.objectDetector6 = ObjectDetector(
                weights, imgsz, conf_thres, iou_thres, device)
            self.anomalyDetector = AnomalyDetector()

    def set_plc_controller(self):
        self.plc_controller1 = PlcController()
        self.plc_controller2 = PlcController()

    def plc_botton(self):
        self.capSignal1 = NoSignal
        try:
            if self.if_connect_1:
                self.if_connect_1 = False
                self.connectButton.setText("连接一部PLC")
                self.plc_controller1.disconnect()
            else:
                self.if_connect_1 = True
                self.connectButton.setText("断开一部PLC")
                ip_1 = self.textBrowser.toPlainText()
                self.plc_controller1.connect(ip_1, 0, 1)
        except:
            if self.if_connect_1:
                print("disconnect error")
            else:
                print("connect error")

    def plc_botton_2(self):
        self.capSignal2 = NoSignal
        try:
            if self.if_connect_2:
                self.if_connect_2 = False
                self.connectButton_2.setText("连接二部PLC")
                self.plc_controller2.disconnect()
            else:
                self.if_connect_2 = True
                self.connectButton_2.setText("断开二部PLC")
                ip_2 = self.textBrowser_2.toPlainText()
                self.plc_controller2.connect(ip_2, 0, 1)
        except:
            if self.if_connect_2:
                print("PLC2 Disconnect Error")
            else:
                print("PLC2 Connect Error")

    def set_modules(self):
        self.connectButton.clicked.connect(self.plc_botton)
        self.connectButton_2.clicked.connect(self.plc_botton_2)

    def set_capture(self):
        user, pwd, channel = "admin", "Jdk111111", 2

        """
         HIKIVISION new version 2017 capture 01
        """
        ip = "192.168.7.21"
        try:
            with eventlet.Timeout(Timeout):
                capIP1 = "rtsp://%s:%s@%s//Streaming/Channels/%d" % (
                    user, pwd, ip, channel)
                # 暂时用视频模拟相机图像
                self.cap1 = cv.VideoCapture(capIP1)
                self.if_opened_1 = True
        except eventlet.timeout.Timeout:
            self.if_opened_1 = False

        """
         HIKIVISION new version 2017 capture 02
        """
        ip = "192.168.7.22"
        try:
            with eventlet.Timeout(Timeout):
                capIP2 = "rtsp://%s:%s@%s//Streaming/Channels/%d" % (
                    user, pwd, ip, channel)
                self.cap2 = cv.VideoCapture(capIP2)
                self.if_opened_2 = True
        except eventlet.timeout.Timeout:
            self.if_opened_2 = False

        """
         HIKIVISION new version 2017 capture 03
        """
        ip = "192.168.7.23"
        try:
            with eventlet.Timeout(Timeout):
                capIP3 = "rtsp://%s:%s@%s//Streaming/Channels/%d" % (
                    user, pwd, ip, channel)
                self.cap3 = cv.VideoCapture(capIP3)
                self.if_opened_3 = True
        except eventlet.timeout.Timeout:
            self.if_opened_3 = False

        """
         HIKIVISION new version 2017 capture 04
        """
        ip = "192.168.7.24"
        try:
            with eventlet.Timeout(Timeout):
                capIP4 = "rtsp://%s:%s@%s//Streaming/Channels/%d" % (
                    user, pwd, ip, channel)
                self.cap4 = cv.VideoCapture(capIP4)
                self.if_opened_4 = True
        except eventlet.timeout.Timeout:
            self.if_opened_4 = False

        """
         HIKIVISION new version 2017 capture 05
        """
        ip = "192.168.7.25"
        try:
            with eventlet.Timeout(Timeout):
                capIP5 = "rtsp://%s:%s@%s//Streaming/Channels/%d" % (
                    user, pwd, ip, channel)
                self.cap5 = cv.VideoCapture(capIP5)
                self.if_opened_5 = True
        except eventlet.timeout.Timeout:
            self.if_opened_5 = False

        """
         HIKIVISION new version 2017 capture 06
        """
        ip = "192.168.7.26"
        try:
            with eventlet.Timeout(Timeout):
                capIP6 = "rtsp://%s:%s@%s//Streaming/Channels/%d" % (
                    user, pwd, ip, channel)
                self.cap6 = cv.VideoCapture(capIP6)
                self.if_opened_6 = True
        except eventlet.timeout.Timeout:
            self.if_opened_6 = False

    def set_thread(self):
        if self.if_opened_1:
            thread1 = threading.Thread(target=self.capThreader1)
            thread1.start()

        if self.if_opened_2:
            thread2 = threading.Thread(target=self.capThreader2)
            thread2.start()

        if self.if_opened_3:
            thread3 = threading.Thread(target=self.capThreader3)
            thread3.start()

        if self.if_opened_4:
            thread4 = threading.Thread(target=self.capThreader4)
            thread4.start()

        if self.if_opened_5:
            thread5 = threading.Thread(target=self.capThreader5)
            thread5.start()

        if self.if_opened_6:
            thread6 = threading.Thread(target=self.capThreader6)
            thread6.start()

    def closeEvent(self, event):
        event.accept()
        os._exit(0)

    def capThreader1(self):
        # ******************************** 摄像头一 ********************************
        while(self.cap1.isOpened()):
            ret, img1 = self.cap1.read()
            if ret:
                # 推理
                # self.anomalyDetector.execute(img)
                img1, xywh1 = self.objectDetector1.inference(img1)

                for i in range(len(self.__restrictedArea[0])):
                    lt = (self.__restrictedArea[0][i][0],
                          self.__restrictedArea[0][i][1])
                    rb = (self.__restrictedArea[0][i][2],
                          self.__restrictedArea[0][i][3])
                    cv.rectangle(img1, lt, rb, (0, 0, 255), 2)

                img1 = cv.resize(img1, (320, 240))

                self.lock1.acquire()

                try:
                    # 显示图像
                    frame = QImage(
                        img1.data, img1.shape[1], img1.shape[0], QImage.Format_BGR888)
                    self.pix1 = QPixmap(frame)

                    self.output1 = "一部坡头: " + self.objectDetector1.output

                    signal = self.__ifAlarm(1, xywh1)
                    if signal != self.capSignal1:
                        self.count_1 += 1
                        if signal == DownSignal and self.count_1 >= 20:
                            self.count_1 = 0
                            now_time = cv.getTickCount()
                            interival = abs(
                                now_time - self.last_time_1) / cv.getTickFrequency()
                            # 每次控制车的时间间隔至少为20s
                            if self.if_connect_1:
                                self.setStateGraph(1, 'Danger')
                                if interival > 30:
                                    self.last_time_1 = cv.getTickCount()
                                    self.plc_controller1.write(11, 0, 2, 1)
                                    self.plc_controller1.write(11, 0, 1, 0)
                                    self.plc_controller1.write(11, 0, 2, 0)
                                    self.plc_controller1.write(11, 0, 1, 1)
                                    self.plc_controller1.write(11, 0, 1, 0)
                                else:
                                    self.infoLabel_1.setText('控制间隔过段')
                            self.capSignal1 = signal
                        elif self.count_1 >= 25:
                            self.count_1 = 0
                            self.setStateGraph(1, 'Normal')
                            self.capSignal1 = signal
                    self.lock1.release()
                except:
                    pass

    def capThreader2(self):
        # ******************************** 摄像头二 ********************************
        while(self.cap2.isOpened()):
            ret, img2 = self.cap2.read()
            if ret:
                # 推理
                # self.anomalyDetector.execute(img)
                img2, xywh2 = self.objectDetector2.inference(img2)

                for i in range(len(self.__restrictedArea[1])):
                    lt = (self.__restrictedArea[1][i][0],
                          self.__restrictedArea[1][i][1])
                    rb = (self.__restrictedArea[1][i][2],
                          self.__restrictedArea[1][i][3])
                    cv.rectangle(img2, lt, rb, (0, 0, 255), 2)

                img2 = cv.resize(img2, (320, 240))

                self.lock2.acquire()

                try:
                    # 显示图像
                    frame = QImage(
                        img2.data, img2.shape[1], img2.shape[0], QImage.Format_BGR888)
                    self.pix2 = QPixmap(frame)

                    self.output2 = "一部偏口: " + self.objectDetector2.output

                    signal = self.__ifAlarm(2, xywh2)
                    if signal != self.capSignal2:
                        self.count_2 += 1
                        if (signal == DownSignal or signal == UpSignal) and self.count_2 >= 20:
                            self.count_2 = 0
                            now_time = cv.getTickCount()
                            interival = abs(
                                now_time - self.last_time_1) / cv.getTickFrequency()
                            if self.if_connect_1:
                                if interival > 30:
                                    self.setStateGraph(2, 'Danger')
                                    self.last_time_1 = cv.getTickCount()
                                    self.plc_controller1.write(11, 0, 2, 1)
                                    self.plc_controller1.write(11, 0, 1, 0)
                                    self.plc_controller1.write(11, 0, 2, 0)
                                    self.plc_controller1.write(11, 0, 1, 1)
                                    self.plc_controller1.write(11, 0, 1, 0)
                                else:
                                    self.infoLabel_2.setText('控制间隔过段')
                            self.capSignal2 = signal
                        elif self.count_2 >= 25:
                            self.count_2 = 0
                            self.setStateGraph(2, 'Normal')
                            self.capSignal2 = signal
                except:
                    print("plc 通信异常")
                self.lock2.release()

    def capThreader3(self):
        # ******************************** 摄像头三 ********************************
        while(self.cap3.isOpened()):
            ret, img3 = self.cap3.read()
            if ret:

                # 推理
                # self.anomalyDetector.execute(img)
                img3, xywh3 = self.objectDetector3.inference(img3)

                for i in range(len(self.__restrictedArea[2])):
                    lt = (self.__restrictedArea[2][i][0],
                          self.__restrictedArea[2][i][1])
                    rb = (self.__restrictedArea[2][i][2],
                          self.__restrictedArea[2][i][3])
                    cv.rectangle(img3, lt, rb, (0, 0, 255), 2)

                img3 = cv.resize(img3, (320, 240))

                self.lock3.acquire()

                try:
                    # 显示图像
                    frame = QImage(
                        img3.data, img3.shape[1], img3.shape[0], QImage.Format_BGR888)
                    self.pix3 = QPixmap(frame)

                    self.output3 = "一部坡底: " + self.objectDetector3.output

                    signal = self.__ifAlarm(3, xywh3)
                    if signal != self.capSignal3:
                        self.count_3 += 1
                        if signal == DownSignal and self.count_3 >= 20:
                            now_time = cv.getTickCount()
                            interival = abs(
                                now_time - self.last_time_1) / cv.getTickFrequency()
                            if self.if_connect_1:
                                self.setStateGraph(3, 'Danger')
                                if interival > 30:
                                    self.last_time_1 = cv.getTickCount()
                                    self.plc_controller1.write(11, 0, 2, 1)
                                    self.plc_controller1.write(11, 0, 1, 0)
                                    self.plc_controller1.write(11, 0, 2, 0)
                                    self.plc_controller1.write(11, 0, 1, 1)
                                    self.plc_controller1.write(11, 0, 1, 0)
                                else:
                                    self.infoLabel_3.setText('控制间隔过段')
                            self.count_3 = 0
                            self.capSignal3 = signal
                        elif self.count_3 >= 25:
                            self.count_3 = 0
                            self.setStateGraph(3, 'Normal')
                            self.capSignal3 = signal
                except:
                    print("plc 通信异常")
                self.lock3.release()

    def capThreader4(self):
        # ******************************** 摄像头四 ********************************
        while(self.cap4.isOpened()):
            ret, img4 = self.cap4.read()

            # 推理
            # self.anomalyDetector.execute(img)
            if ret:
                img4, xywh4 = self.objectDetector4.inference(img4)
                for i in range(len(self.__restrictedArea[3])):
                    lt = (self.__restrictedArea[3][i][0],
                          self.__restrictedArea[3][i][1])
                    rb = (self.__restrictedArea[3][i][2],
                          self.__restrictedArea[3][i][3])
                    cv.rectangle(img4, lt, rb, (0, 0, 255), 2)

                img4 = cv.resize(img4, (320, 240))

                # 显示图像
                frame = QImage(
                    img4.data, img4.shape[1], img4.shape[0], QImage.Format_BGR888)
                self.pix4 = QPixmap(frame)

                self.output4 = "二部坡头: " + self.objectDetector4.output

                signal = self.__ifAlarm(4, xywh4)
                if signal != self.capSignal4:
                    self.count_4 += 1
                    if signal == DownSignal and self.count_4 >= 20:
                        now_time = cv.getTickCount()
                        interival = abs(
                            now_time - self.last_time_2) / cv.getTickFrequency()
                        if self.if_connect_2:
                            self.setStateGraph(4, 'Danger')
                            if interival > 30:
                                self.last_time_2 = cv.getTickCount()
                                self.plc_controller2.write(11, 0, 2, 1)
                                self.plc_controller2.write(11, 0, 1, 0)
                                self.plc_controller2.write(11, 0, 2, 0)
                                self.plc_controller2.write(11, 0, 1, 1)
                                self.plc_controller2.write(11, 0, 1, 0)
                            else:
                                self.infoLabel_4.setText('控制间隔过段')
                        self.count_4 = 0
                        self.capSignal4 = signal
                    elif self.count_4 >= 25:
                        self.count_4 = 0
                        self.setStateGraph(4, 'Normal')
                        self.capSignal4 = signal

    def capThreader5(self):
        # ******************************** 摄像头五 ********************************
        while(self.cap6.isOpened()):
            ret, img5 = self.cap6.read()
            # img = cv.imread("./snow.jpg")
            # 推理
            # self.anomalyDetector.execute(img)
            if ret:
                img5, xywh5 = self.objectDetector5.inference(img5)

                for i in range(len(self.__restrictedArea[4])):
                    lt = (self.__restrictedArea[4][i][0],
                          self.__restrictedArea[4][i][1])
                    rb = (self.__restrictedArea[4][i][2],
                          self.__restrictedArea[4][i][3])
                    cv.rectangle(img5, lt, rb, (0, 0, 255), 2)

                img5 = cv.resize(img5, (320, 240))

                # 显示图像
                frame = QImage(
                    img5.data, img5.shape[1], img5.shape[0], QImage.Format_BGR888)
                self.pix5 = QPixmap(frame)

                self.output5 = "二部偏口: " + self.objectDetector5.output

                signal = self.__ifAlarm(5, xywh5)
                if signal != self.capSignal5:
                    self.count_5 += 1
                    if (signal == DownSignal or signal == UpSignal) and self.count_5 >= 20:
                        now_time = cv.getTickCount()
                        interival = abs(
                            now_time - self.last_time_2) / cv.getTickFrequency()
                        if self.if_connect_2:
                            self.setStateGraph(5, 'Danger')
                            if interival > 30:
                                self.last_time_2 = cv.getTickCount()
                                self.plc_controller2.write(11, 0, 2, 1)
                                self.plc_controller2.write(11, 0, 1, 0)
                                self.plc_controller2.write(11, 0, 2, 0)
                                self.plc_controller2.write(11, 0, 1, 1)
                                self.plc_controller2.write(11, 0, 1, 0)
                            else:
                                self.infoLabel_5.setText('控制间隔过段')
                        self.count_5 = 0
                        self.capSignal5 = signal
                    elif self.count_5 >= 25:
                        self.count_5 = 0
                        self.setStateGraph(5, 'Normal')
                        self.capSignal5 = signal

    def capThreader6(self):
        # ******************************** 摄像头六 ********************************
        while(self.cap5.isOpened()):
            ret, img6 = self.cap5.read()

            if ret:
                # 推理
                # self.anomalyDetector.execute(img)
                img6, xywh6 = self.objectDetector6.inference(img6)

                for i in range(len(self.__restrictedArea[5])):
                    lt = (self.__restrictedArea[5][i][0],
                          self.__restrictedArea[5][i][1])
                    rb = (self.__restrictedArea[5][i][2],
                          self.__restrictedArea[5][i][3])
                    cv.rectangle(img6, lt, rb, (0, 0, 255), 2)

                img6 = cv.resize(img6, (320, 240))

                # 显示图像
                frame = QImage(
                    img6.data, img6.shape[1], img6.shape[0], QImage.Format_BGR888)
                self.pix6 = QPixmap(frame)

                self.output6 = "二部坡底: " + self.objectDetector6.output

                signal = self.__ifAlarm(6, xywh6)
                if signal != self.capSignal6:
                    self.count_6 += 1
                    if signal == DownSignal and self.count_6 >= 20:
                        now_time = cv.getTickCount()
                        interival = abs(
                            now_time - self.last_time_2) / cv.getTickFrequency()
                        if self.if_connect_2:
                            self.setStateGraph(6, 'Danger')
                            if interival > 30:
                                self.last_time_2 = cv.getTickCount()
                                self.plc_controller2.write(11, 0, 2, 1)
                                self.plc_controller2.write(11, 0, 1, 0)
                                self.plc_controller2.write(11, 0, 2, 0)
                                self.plc_controller2.write(11, 0, 1, 1)
                                self.plc_controller2.write(11, 0, 1, 0)
                            else:
                                self.infoLabel_6.setText('控制间隔过段')
                        self.count_6 = 0
                        self.capSignal6 = signal
                    elif self.count_6 >= 25:
                        self.count_6 = 0
                        self.setStateGraph(6, 'Normal')
                        self.capSignal6 = signal

    def QLabelView1(self):
        """
        QLabelView
        将图像加载入控件中
        """
        # start = cv.getTickCount()

        # end = cv.getTickCount()
        # time = (end - start) / cv.getTickFrequency()

        self.MainGraph11.setPixmap(self.pix1)
        self.MainGraph11.show()

        output = self.output1 + self.output2 + self.output3 + \
            self.output4 + self.output5 + self.output6 + '\n'
        # print(output)
        # 文本框输出
        self.printf(output)

    def QLabelView2(self):
        self.MainGraph12.setPixmap(self.pix2)
        self.MainGraph12.show()

    def QLabelView3(self):
        self.MainGraph13.setPixmap(self.pix3)
        self.MainGraph13.show()

    def QLabelView4(self):
        self.MainGraph21.setPixmap(self.pix4)
        self.MainGraph21.show()

    def QLabelView5(self):
        self.MainGraph22.setPixmap(self.pix5)
        self.MainGraph22.show()

    def QLabelView6(self):
        self.MainGraph23.setPixmap(self.pix6)
        self.MainGraph23.show()

    def printf(self, mystr):
        """
        printf
        调用该函数在文本框中输出字符串

        Args:
            mystr ([str]): 打印信息
        """
        # 在文本框后打入字符串
        self.SandBrowser.append(mystr)
        self.cursor = self.SandBrowser.textCursor()
        # 光标移到最后，这样就会自动显示出来
        self.SandBrowser.moveCursor(self.cursor.End)
        # 一定加上这个功能，不然有卡顿
        QtWidgets.QApplication.processEvents()

    def setStateGraph(self, index, state):
        """
        setStateGraph
        设置StateGraph状态

        Args:
            state ([str]): 状态
        """
        carState = ""
        # 根据标志设置状态
        if state == 'Error':
            self.state = self.ErrorState
        elif state == 'Danger':
            self.state = self.DangerState
            carState = "停止"
        elif state == 'Normal':
            self.state = self.NormalState
            carState = "运行"
        # 显示图像
        frame = QImage(
            self.state, self.state.shape[1], self.state.shape[0], self.state.shape[1] * 3, QImage.Format_BGR888)
        pix = QPixmap.fromImage(frame)

        if index == 1:
            self.StateGraph.setPixmap(pix)
        elif index == 2:
            self.StateGraph_2.setPixmap(pix)
        elif index == 3:
            self.StateGraph_3.setPixmap(pix)
        elif index == 4:
            self.StateGraph_4.setPixmap(pix)
        elif index == 5:
            self.StateGraph_5.setPixmap(pix)
        elif index == 6:
            self.StateGraph_6.setPixmap(pix)

        if index <= 3 and state != 'Error':
            self.infoLabel_1.setText("一部坡头猴车" + carState)
            self.infoLabel_2.setText("一部偏口猴车" + carState)
            self.infoLabel_3.setText("一部坡底猴车" + carState)
        elif index <= 6 and state != 'Error':
            self.infoLabel_4.setText("二部坡头猴车" + carState)
            self.infoLabel_5.setText("二部偏口猴车" + carState)
            self.infoLabel_6.setText("二部坡底猴车" + carState)

    def __ifAlarm(self, index, rec):
        for j in range(len(rec)):
            down_iou = self.__calcIOU(
                rec[j], self.__restrictedArea[index - 1][0])
            if down_iou >= 0.03:
                return DownSignal
            if (index == 2 or index == 4) and len(self.__restrictedArea[index - 1]) >= 2:
                up_iou = self.__calcIOU(
                    rec[j], self.__restrictedArea[index - 1][1])
                if up_iou >= 0.03:
                    return UpSignal
        return NoSignal

    def __calcIOU(self, r1, r2):
        # 获取box1左上角的坐标
        x1min, y1min = r1[0], r1[1]
        # 获取box1右下角的坐标
        x1max, y1max = r1[2], r1[3]
        # 获取box1的面积
        s1 = (r1[2] - r1[0]) * (r1[3] - r1[1])
        if not isinstance(x1min, list):
            x1min = x1min.cpu().numpy()
            x1max = x1max.cpu().numpy()
            y1min = y1min.cpu().numpy()
            y1max = y1max.cpu().numpy()

        # 获取box2左上角的坐标
        x2min, y2min = r2[0], r2[1]
        # 获取box2右下角的坐标
        x2max, y2max = r2[2], r2[3]
        # 获取box2的面积
        s2 = (r2[2] - r2[0]) * (r2[3] - r2[1])

        # 计算相交矩形框的坐标
        xmin = np.maximum(x1min, x2min)  # 左上角的横坐标
        ymin = np.maximum(y1min, y2min)  # 左上角的纵坐标
        xmax = np.minimum(x1max, x2max)  # 右下角的横坐标
        ymax = np.minimum(y1max, y2max)  # 右下角的纵坐标

        inter_h = np.maximum(ymax - ymin, 0.)
        inter_w = np.maximum(xmax - xmin, 0.)
        intersection = inter_h * inter_w

        union = s1 + s2 - intersection
        iou = intersection / union
        return iou
